﻿CREATE PROCEDURE [maint].[IsDiffBackupRequired]
@DbName [sysname], @BackupSetName [sysname], @Required BIT=0 OUTPUT, @OutputDiagnostics BIT=0
AS
BEGIN
	IF(@OutputDiagnostics = 1)
		BEGIN
			PRINT OBJECT_NAME(@@PROCID)
			PRINT N'	@DbName = N''' + ISNULL(@DbName,N'NULL') + ''''
			PRINT N'	@BackupSetName = N''' + ISNULL(@BackupSetName,N'NULL') + ''''
		END

	IF(@DbName IN (N'master',N'model','tempdb'))
		RETURN(0)

	DECLARE @DiffBackupSchedule int
	SET @DiffBackupSchedule = maint.GetDiffBackupSchedule(@DbName)

	DECLARE @DiffBackupTime int
	SET @DiffBackupTime = maint.GetDiffBackupTime(@DbName)

	SET DATEFIRST 1

	IF ((@DiffBackupSchedule & POWER(2,DATEPART(dw,GETDATE())-1)) = 0)
	OR (GETDATE() < util.ChangeDateTime(GETDATE(),@DiffBackupTime))
	OR EXISTS(
		SELECT * 
		FROM [msdb].dbo.backupset
		WHERE  ([name] = @BackupSetName)
			AND([type] = N'I')
			AND([expiration_date] > GETDATE())
	)
		SET @Required = 0
	ELSE
		SET @Required = 1

	RETURN(0)
END